/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        ListNode *toDelete = nullptr;
        while (head != nullptr && head->val == val)
        {
            toDelete = head;
            head = head->next;
            delete toDelete;
            toDelete = nullptr;
        }
        if (head == nullptr)
        {
            return nullptr;
        }
        ListNode *cur = head;
        ListNode *next = head->next;
        while (next != nullptr)
        {
            if (next->val == val)
            {
                cur->next = next->next;
                delete next;
                next = cur->next;
            }
            else
            {
                cur = next;
                next = next->next;
            }
        }
        return head;
    }
};